require 'socket'
require 'thread'
class STUNTCHKServer
  def initialize(host,port)
    @server = TCPServer.new(host, port)
    @server.listen(5)
  end
  def run
    Thread.new do
      serve
    end
  end
  def test(socket,daddr)
    #Thread.new do
    begin
    	data=socket.read(10)
		myaddr2=Socket.pack_sockaddr_in(data.to_i,daddr)
    	#p data
    	#p socket.peeraddr[2]
    	if !(data.nil?) then
	    	#for i in 0..4
	    	begin
    			webSocket = Socket::new(Socket::AF_INET,Socket::SOCK_STREAM,0)
		    	webSocket.setsockopt( Socket::SOL_SOCKET, Socket::SO_REUSEADDR, 1 ) 
    			myaddr =Socket.pack_sockaddr_in(12346,"84.234.17.41")
    			webSocket.bind(myaddr)
		    	webSocket.connect(myaddr2)
    			#webSocket=TCPSocket::new(socket.peeraddr[2], data.to_i,"84.234.17.41",12346 )
    			#webSocket.send("Kerjordando");
		   	rescue
   				sleep(10)
		   	p $!
   			ensure
	 		   	webSocket.close
	 		end
	    	begin
		    	p 'second'
    			webSocket = Socket::new(Socket::AF_INET,Socket::SOCK_STREAM,0)
		    	p '1'
		    	webSocket.setsockopt( Socket::SOL_SOCKET, Socket::SO_REUSEADDR, 1 ) 
		    	p '2'
    			myaddr =Socket.pack_sockaddr_in(12346,"84.234.17.41")
		    	p '3'
    			webSocket.bind(myaddr)
		    	p '4'
		    	webSocket.connect(myaddr2)
		    	p '5'
		    	sleep(10)
    			#webSocket=TCPSocket::new(socket.peeraddr[2], data.to_i,"84.234.17.41",12346 )
    			#webSocket.send("Kerjordando");
		   	rescue
		   	p $!
   			ensure
		    	p 'yy'
	 		   	webSocket.close
	 		end
	       		#	sleep 4
    		#end
    	end
   	rescue
   	ensure
	    socket.close
	end
   	#end
  end
  def serve
    while(socket=@server.accept)
    	test(socket,socket.peeraddr[2])
    end
  end
end
if $0==__FILE__ then
#  Test.socketAddress
  s=STUNTCHKServer.new("84.234.17.41",12345)
  s.serve
end
